import { ApiRequest } from '@api/basePage'
import { cityTreeDataUtils } from '@/assets/js/commonUtils'
const state = {
  citySelectedList: [], // 已选择城市对象集合
  selectedCityListStr: {}, // 已选城市名字、code拼接字符串组成的对象
  treeCityData: [], // 请求到的当前模态框的城市列表
}

const mutations = {
  /* 设置当前已选城市集合 */
  SET_SELECTED_CITY_LIST: (state, data) => {
    let appliedArea = ''
    let appliedAreaName = ''
    if (data.length === 0) {
      state.citySelectedList = []
      appliedArea = ''
      appliedAreaName = ''
    } else {
      state.citySelectedList = []
      data.forEach(item => {
        if (item.children === undefined) {
          appliedArea += item.code + ' ';
          appliedAreaName += item.title + ' ';
          state.citySelectedList.push({
            cityCode: item.code,
            cityName: item.title,
            cityUuid: item.uuid,
          })
        }
      })
    }
    appliedArea = appliedArea.slice(0, appliedArea.length - 1)
    appliedAreaName = appliedAreaName.slice(0, appliedAreaName.length - 1)
    state.selectedCityListStr = {
      appliedArea,
      appliedAreaName
    }
  },
  /* 设置城市列表 */
  SET_CITY_TREE: (state, data) => {
    let dataList = cityTreeDataUtils(data)
    state.treeCityData = [
      {
        title: '全选',
        expand: true,
        checked: false,
        children: dataList
      }
    ]
  },
  /* 改变城市列表的checked */
  CHANGE_CITY_CHECKED: (state, data) => {
    let treeCityData = state.treeCityData
    let citySelectedList = state.citySelectedList
    let sourceDataList = treeCityData[0]
    sourceDataList.checked = false
    sourceDataList.children.forEach(value => {
      value.checked = false
      value.children.length !== 0 && value.children.forEach(item => {
        item.checked = false
      })
    })
    citySelectedList.length !== 0 && citySelectedList.forEach(value => {
      treeCityData[0].children.forEach((item, index) => {
        let i = _.findIndex(item.children, elem => { return elem.code === value.cityCode })
        if (i !== -1) { state.treeCityData[0].children[index].children[i].checked = true }
      })
    })
  },
  /* 提交后重置数据 */
  RESET_CITY_DATA: (state, data) => {
    state.citySelectedList = []
    state.selectedCityListStr = {}
    state.treeCityData = []
  }
}

const actions = {
  getCityTreeList ({ state, commit }, { payload: { data, cb } }) {
    let { url, type, params } = data
    return new Promise((resolve, reject) => {
      ApiRequest(url, type, params, true).then(res => {
        if (cb) { cb(res) }
        if (res.retStatus === '1') {
          commit('SET_CITY_TREE', res.retData)
        }
        resolve(res.retData)
      }).catch(error => {
        reject(error)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
